#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>

#define NETAV_HOST	"192.168.1.63"
#define NETAV_PORT	"5026"

#define MSG_HEAD \
	"NOTIFY LocationFree_BaseStation\r\n"\
	"Version: 3.000\r\n"\
	"SoftVersion: 3.000\r\n"\
	"NetAV_Host: " NETAV_HOST "\r\n"\
	"NetAV_Port: " NETAV_PORT "\r\n"\
	"Identifier: B9100055846C\r\n"\
	"Model: LF-B1EU\r\n"\
	"Nonce: 2d1b98bdb07a745d4253284974dacfe6\r\n"\
	"NETIF: 1\r\n"

#define MSG_NORMAL \
	MSG_HEAD \
	"BaseStation_Mode: NORMAL\r\n"\
	"\r\n"

#define MSG_REGISTRATION \
	MSG_HEAD \
	"BaseStation_Mode: REGISTRATION\r\n"\
	"\r\n"


int
main(int argc, char **argv)
{
	struct sockaddr_in local, remote;
	int s, len;
	socklen_t slen;
	char buf[0x100];
	char *msg;

	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
		perror("socket");
		return -1;
	}

	memset(buf, 0x0, sizeof(buf));
	slen = sizeof(remote);
	local.sin_family = AF_INET;
	local.sin_port = htons(7777);
	local.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(s, (struct sockaddr *) &local, sizeof(local)) == -1) {
		perror("bind");
		return -1;
	}

	if (argc > 1)
		msg = MSG_REGISTRATION;
	else
		msg = MSG_NORMAL;

	printf("%s\n", msg);

	while (1) {
		if ((len = recvfrom(s, buf, 0x100, 0, (struct sockaddr *) &remote, &slen)) == -1) {
			perror("recvfrom");
			return -1;
		}
		printf("recv %d bytes from %s:%d\nData: %s\n\n",
				len,
				inet_ntoa(remote.sin_addr),
				ntohs(remote.sin_port),
				buf);
		sendto(s, msg, strlen(msg), 0, (struct sockaddr *) &remote, sizeof(remote));
	}

	close(s);
	return 0;
}
